#!/bin/bash
##

GERBV=$(which gerbv)

set -e

# When hand-drilling, we want the holes small.
SMALL_HOLES=1
RESOLUTION_DPI=1500
OUTDIR=""

if [ $# -lt 1 ] ; then
    echo "usage: $0 [options] <gerber-file> [<gerber-file>...]"
    echo -e "\t-d <outdir>  : Directory to write PNG files to. Default: wherever the gerber files are."
    echo -e "\t-r <dpi>     : Resolution in DPI. Default 1500dpi"
    echo -e "\t-l           : Large holes: do not narrow drill holes"

    echo "Output to PNG filenames based on the gerber filenames + '.png'"
    echo
    echo "If you also give the drill file, 'holes' are generated in the copper layers."
    echo
    echo "To have all corresponding PNG images aligned with each other"
    echo "(think of exposure copper and solder mask in two rounds),"
    echo "always pass in all needed gerber files."
   exit 1
fi

while : ; do
    case $1 in
	-d) OUTDIR=$2; mkdir -p $OUTDIR ; shift; shift
	    ;;
	-l) SMALL_HOLES=0; shift
	    ;;
	-r) RESOLUTION_DPI=$2 ; shift ; shift
	    ;;
	*) break
	   ;;
    esac
done

if [ -z "$GERBV" ] ; then
    echo "This requires the 'gerbv' binary to be installed."
    exit 1
fi

SHOWN_COLOR="-f#000000ff"   # Black.
HIDDEN_COLOR="-f#fefefe00"  # almost white, force layer to be in BoundingBox
DRILL_COLOR="-f#ffffffff"   # white holes

for f in "$@" ; do
    if [ ! -f "$f" ] ; then
	echo "Not a file $f"
	exit 1
    fi
    if [[ "$f" == *.png ]] ; then
	continue
    fi
    if [[ "$f" == *.drl ]] ; then
	if [ $SMALL_HOLES -eq 0 ] ; then
	    DRILL_LAYER="$DRILL_COLOR $f"
	else
	    sed 's/^T[0-9]*C.*/;\0/' < "$f" > /tmp/orig.$$.drl
	    ( for i in `seq 1 9` ; do echo "T0$i 0.01" ; done ) > /tmp/fake.$$.drl
	    DRILL_LAYER="$DRILL_COLOR /tmp/orig.$$.drl -t/tmp/fake.$$.drl"
	fi
    else
	BACKGROUND_LAYERS="$BACKGROUND_LAYERS $HIDDEN_COLOR $f"
	ALL_THE_FILES="$ALL_THE_FILES $f"
    fi
done

for f in $ALL_THE_FILES ; do
    if [[ "$f" == *.g?l || "$f" == *.g[23]* ]] ; then  # gtl, gbl or inner
	# Copper layers should have the drill layer ... if available
	$GERBV -xps -o/tmp/gerbvtmp.$$.ps $DRILL_LAYER $SHOWN_COLOR "$f" $BACKGROUND_LAYERS 2>/dev/null
    else
	$GERBV -xps -o/tmp/gerbvtmp.$$.ps $SHOWN_COLOR "$f" $BACKGROUND_LAYERS 2>/dev/null
    fi

    # Depending if we have an out-dir, we write it there or
    if [ -z "$OUTDIR" ] ; then
	OUTFILE="$f.png"
    else
	OUTFILE="$OUTDIR/`basename $f`.png"
    fi

    # .. convert to PNG, set DPI.
    `dirname $0`/ps2bwpng $RESOLUTION_DPI /tmp/gerbvtmp.$$.ps > "$OUTFILE"
    rm -f /tmp/gerbvtmp.$$.ps
done

rm -f /tmp/*.$$.drl /tmp/gerbvtmp.$$.ps
